<?php

namespace app\common\model;

use think\Model;
use think\Db;

/**
 * 用户签到表
 */
class UserSign Extends Model
{
    /**
     * 签到
     * @param $user_id
     */
    public function makeSign($user_id){
        $ishas = Db::name('user_sign')->where('user_id',$user_id)->find();
        if($ishas){

            $isSignToday = $this->isSignToday($user_id);
            if($isSignToday){
                //今日已签到
                $result = ['code' => 0, 'msg' => '今日已签到', 'data' => ''];

            }else{
                Db::name('user_sign')->where('user_id',$user_id)->update(['last_time'=> time()]);
                $res = Db::name('user_sign')->where('user_id',$user_id)->setInc('count');

                if($res !== false){
                    $result = ['code' => 0, 'msg' => '签到成功', 'data' => ''];
                }else{
                    $result = ['code' => 0, 'msg' => '签到失败', 'data' => ''];
                }
            }



        }else{
            //第一次签到
            $data = [
                'user_id' => $user_id,
                'count' => 1,
                'last_time' => time()
            ];
            $res = self::create($data);

            if($res){

                $result = ['code' => 0, 'msg' => '签到成功', 'data' => ''];
            }else{
                $result = ['code' => 0, 'msg' => '签到失败', 'data' => ''];
            }

        }

        return $result;



    }

    public function isSignToday($user_id){
       $res = Db::name('user_sign')->where('user_id',$user_id)->whereTime('last_time','today')->find();
       if($res){
           return true;
       }else{
           return false;
       }
    }

    public function giveUserScore($user_id){
        $signScore = Db::name('config')->where(['name' => 'sign_score'])->value('value');
        $memo = '用户签到奖励积分';
        change_user_score_log($user_id,$signScore,$memo); //积分记录表
    }

}